import 'dart:io';

import 'package:async_wallpaper/async_wallpaper.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'package:wallpaper/components/button/action_icon_btn.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/generated/l10n.dart';

class LocalVideo extends StatefulWidget {
  const LocalVideo({super.key});

  @override
  LocalVideoState createState() => LocalVideoState();
}

class LocalVideoState extends State<LocalVideo> {
  String videoUrl = '';
  late VideoPlayerController _videoController;
  bool isVideoInitialized = false;

  Future<void> _pickVideoFromGallery() async {
    final XFile? video =
        await ImagePicker().pickVideo(source: ImageSource.gallery);
    if (video != null) {
      // Dispose the previous controller if it's initialized
      if (_videoController.value.isInitialized) {
        await _videoController.dispose();
      }

      setState(() {
        videoUrl = video.path;
        _videoController = VideoPlayerController.file(File(video.path));
        _videoController.initialize().then((_) {
          setState(() {
            isVideoInitialized = true;
          });
          _videoController.play();
          _videoController.setLooping(true);
        });
      });
    }
  }

  void setVideoPaper() async {
    if (videoUrl.isEmpty) {
      BotToast.showText(text: S.of(context).s6);
    } else {
      try {
        await AsyncWallpaper.setLiveWallpaper(
          filePath: videoUrl,
          goToHome: false,
        );
      } on PlatformException {
        BotToast.showText(text: S.of(context).s5, backgroundColor: Colors.red);
      }
    }
  }

  @override
  void initState() {
    super.initState();
    _videoController = VideoPlayerController.file(File(''));
  }

  @override
  void dispose() {
    _videoController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          if (videoUrl.isEmpty)
            Center(
              child: Empty(),
            ),
          if (isVideoInitialized)
            Center(
              child: AspectRatio(
                aspectRatio: _videoController.value.aspectRatio,
                child: FittedBox(
                  fit: BoxFit.cover,
                  child: SizedBox(
                    width: _videoController.value.size.width,
                    height: _videoController.value.size.height,
                    child: VideoPlayer(_videoController),
                  ),
                ),
              ),
            ),
          Positioned(
            top: 0,
            bottom: 0,
            right: 15,
            child: Center(
              child: Column(
                spacing: 10,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ActionIconButton(
                      icon: Icons.add, onTap: _pickVideoFromGallery),
                  ActionIconButton(icon: Icons.ad_units, onTap: setVideoPaper),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}
